﻿#include "additem.h"
#include "ui_additem.h"

AddItem::AddItem(QWidget *parent, const QString &table) :
    QDialog(parent),
    table_(table),
    ui(new Ui::AddItem)
{
    ui->setupUi(this);

    updateTopic();
}

AddItem::~AddItem()
{
    delete ui;
}

void AddItem::setTopic(const QString &topic)
{
    ui->topics->setCurrentText(topic);
}

void AddItem::updateTopic()
{
    if(ui->topics->count() != 0)
        ui->topics->clear();

    QStringList items=sp_getTopic(table_);
    if(!items.isEmpty())
        ui->topics->addItems(items);

    ui->topics->addItem(MANUAL_INPUT);
    ui->topics->setCurrentIndex(-1);
}

bool AddItem::addItem(const QString &topic,
                      const QString &label,
                      const QString &detail,
                      const QString &addition)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (topic,label,detail,addition) values (?,?,?,?)")
                  .arg(table_));
    query.addBindValue(topic);
    query.addBindValue(label);
    query.addBindValue(detail);
    query.addBindValue(addition);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void AddItem::on_btn_submit_clicked()
{
    QString topic;
    if(ui->topic->isEnabled())
        topic=ui->topic->text().trimmed();
    else
        topic=ui->topics->currentText();

    if(topic.isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("输入无效"),
                             QStringLiteral("位置不能为空！"));
        return;
    }

    QString label=ui->label->text().trimmed();
    if(label.isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("输入无效"),
                             QStringLiteral("产品名称不能为空！"));
        return;
    }

    QString detail=ui->detail->text().trimmed();
    QString addition=ui->addition->text().trimmed();
    if(addItem(topic,label,detail,addition))
        accept();
    else
        QMessageBox::warning(this,QStringLiteral("异常情况"),
                             QStringLiteral("无法提交数据！"));
}

void AddItem::on_topics_currentTextChanged(const QString &text)
{
    if(text == MANUAL_INPUT)
    {
        ui->topic->clear();
        ui->topic->setEnabled(true);
    }
    else
    {
        ui->topic->setText(text);
        ui->topic->setEnabled(false);
    }
}
